package com.android.ddfafu.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.android.ddfafu.MapApplication;
import com.android.ddfafu.R;
import com.android.ddfafu.domian.Data;
import com.android.ddfafu.domian.ResultInfo;
import com.android.ddfafu.utils.Const;
import com.android.ddfafu.utils.UserHttpUtil;
import com.android.ddfafu.result.UserData;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Login_activity extends AppCompatActivity {
    private MapApplication application;
    private EditText username;
    private EditText password;
    private Button loginBtn;
    private Button regisBtn;
    private SharedPreferences sp;
    private UserData userData;
    private CheckBox checkBox;
    private TextView login_forget;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ActivityCompat.requestPermissions(Login_activity.this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},1);
        //绑定账号输入框
        username = findViewById(R.id.loginusername);
        //绑定密码输入框
        password = findViewById(R.id.loginpassword);
        //绑定注册按钮
        loginBtn = findViewById(R.id.loginbutton);
        regisBtn = findViewById(R.id.registbutton);
        login_forget = findViewById(R.id.login_forget);
        login_forget.setOnClickListener(v -> {
            Intent intent = new Intent(this,forget_activity.class);
            startActivity(intent);
        });

        userData = new UserData();

        loginBtn.setOnClickListener(v -> {
            String loginUsername = username.getText().toString();
            String loginPassword = password.getText().toString();

            if(StringUtils.isEmpty(loginUsername)) {
                username.setHint("邮箱不能为空");
                username.setHintTextColor(getResources().getColor(R.color.red));
                return;
            }else {
                String pattern = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
                if (!loginUsername.matches(pattern)){
                    username.setText("");
                    username.setHint("邮箱格式错误");
                    username.setHintTextColor(getResources().getColor(R.color.red));
                    return;
                }
            }
            if (StringUtils.isEmpty(loginPassword)){
                password.setHint("密码不能为空");
                password.setHintTextColor(getResources().getColor(R.color.red));
                return;
            }

            //将用户数据 不一定是正确的数据 存入userData
            userData.setUsername(loginUsername);
            userData.setPassword(loginPassword);

            loginWithOkHttp(Const.SERVER_URL_LOGIN, loginUsername, loginPassword);
        });
        //点击注册按钮跳转到注册页面
        regisBtn = findViewById(R.id.registbutton);
        regisBtn.setOnClickListener(v -> {
            Intent i = new Intent(Login_activity.this, Register_activity.class);
            // 启动
            startActivity(i);
            overridePendingTransition(R.anim.out_to_left, R.anim.in_from_right);
        });

        sp = this.getSharedPreferences("userData", Context.MODE_PRIVATE);
        checkBox = findViewById(R.id.login_remember);
        String aSwitch = getIntent().getStringExtra("SWITCH");
        if (aSwitch == null) {
            //从本地存储的用户信息中取出 第一次登陆记住的账号密码 自动登陆
            boolean remember = sp.getBoolean("REMEMBER", false);
            if (remember) {
                String username = sp.getString("USERNAME", "");
                String password = sp.getString("PASSWORD", "");
                String name = sp.getString("NAME", "");
                String token = sp.getString("TOKEN", "");
                System.out.println(username + password);
                if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                    Intent i = new Intent(Login_activity.this, MainActivity.class);
                    i.putExtra("name", name);
                    i.putExtra("username", username);
                    startActivity(i);

                }
            }
        }
    }

    public void loginWithOkHttp(String address, String account, String password) {
        UserHttpUtil.loginWithOkHttp(address, account, password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
                Toast.makeText(Login_activity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                userData.clearData();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                final String responseData = response.body().string();
                System.out.println(responseData);
                ObjectMapper mapper = new ObjectMapper();
                final ResultInfo info = mapper.readValue(responseData, ResultInfo.class);
                final Data data = info.getData();
                runOnUiThread(() -> {
                    if (info.isFlag()) {
                        String name = info.getData().getUser().getName();
                        String username = info.getData().getUser().getUsername();
                        String token = info.getData().getToken();

                        //第一次登陆
                        System.out.println("----第一次登陆----");
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("USERNAME",userData.getUsername());
                        edit.putString("PASSWORD",userData.getPassword());
                        edit.putString("NAME",info.getData().getUser().getName());
                        edit.putString("TOKEN",info.getData().getToken());
                        edit.putBoolean("REMEMBER",checkBox.isChecked());
                        edit.apply();
                        edit.commit();

                        //从Application中获取 用户信息
                        UserData userData = new UserData();
                        userData.setToken(token);
                        userData.setUsername(username);
                        application = (MapApplication)getApplication();
                        application.putUserInfo(userData);

                        Intent i = new Intent(Login_activity.this, MainActivity.class);
                        i.putExtra("name",name);
                        i.putExtra("username",username);
                        Toast.makeText(Login_activity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        startActivity(i);
                    } else {
                        Toast.makeText(Login_activity.this, info.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
